<?php

namespace App\Component\Smarty;

use Teeb\Base\Application;

class SmartyManager
{
    protected $app;

    protected $smarty;

    public function __construct(Application $app)
    {
        $this->app = $app;

        require_once($app->basePath() . '/library/smarty/libs/Smarty.class.php');

        $smarty = new \Smarty();

        $templateDir = $app->viewPath();
        $compileDir = $app->runtimePath() . '/smarty/templates_c/';
        $cacheDir = $app->runtimePath() . '/smarty/cache/';
        if (!file_exists($compileDir)) {
            mkdir($compileDir, 0777, true);
        }
        if (!file_exists($cacheDir)) {
            mkdir($cacheDir, 0777, true);
        }

        $smarty->setTemplateDir($templateDir);
        $smarty->setCompileDir($compileDir);
        $smarty->setCacheDir($cacheDir);

        $this->smarty = $smarty;
    }
    public function __call($method, $param)
    {
        return call_user_func_array(array($this->smarty, $method), $param);  
    }    
    public function render($view, $data = [])
    {
        $this->smarty->clearAllAssign();

        $this->smarty->assign($data);

        $template = $this->getTemplateFile($view);

        return $this->smarty->display($template);
    }

    public function getTemplateFile($view)
    {
        return "{$view}.tpl";
    }
}